class Solution
{
public:
    long long minCost(vector<int> &basket1, vector<int> &basket2)
    {
        unordered_map<int, int> basket1Count, basket2Count;
        unordered_set<int> fruitKinds;
        for (int fruit : basket1)
        {
            ++basket1Count[fruit];
            fruitKinds.insert(fruit);
        }
        for (int fruit : basket2)
        {
            ++basket2Count[fruit];
            fruitKinds.insert(fruit);
        }
        map<int, int> diffCount;
        for (auto fruit : fruitKinds)
        {
            int diff = basket1Count[fruit] - basket2Count[fruit];
            if (diff != 0)
            {
                diffCount[fruit] = diff;
            }
        }
        vector<int> swapOut1, swapOut2;
        for (auto &[fruit, diff] : diffCount)
        {
            bool neg = (diff < 0);
            if (neg)
            {
                diff = -diff;
            }
            if (diff & 1)
            {
                return -1;
            }
            if (neg)
            {
                swapOut2.insert(swapOut2.end(), diff >> 1, fruit);
            }
            else
            {
                swapOut1.insert(swapOut1.end(), diff >> 1, fruit);
            }
        }
        int s1 = swapOut1.size();
        int s2 = swapOut2.size();
        if ((s1 - s2) % 2 != 0)
        {
            return -1;
        }

        int minFruit = min(*min_element(basket1.begin(), basket1.end()), *min_element(basket2.begin(), basket2.end()));

        int pos1 = 0;
        int pos2 = 0;
        long long result = 0;
        while (pos1 < s1 && pos2 < s2)
        {
            if (swapOut1[pos1] < swapOut2[pos2])
            {
                if (swapOut1[pos1] < 2 * minFruit)
                {
                    result += swapOut1[pos1];
                }
                else
                {
                    result += 2 * minFruit;
                }
                ++pos1;
                --s2;
            }
            else
            {
                if (swapOut2[pos2] < 2 * minFruit)
                {
                    result += swapOut2[pos2];
                }
                else
                {
                    result += 2 * minFruit;
                }
                ++pos2;
                --s1;
            }
        }
        result += (s1 - pos1) / 2LL * minFruit;
        result += (s2 - pos2) / 2LL * minFruit;
        return result;
    }
};